import { useUserStore } from "@/store/user"
import axios from "axios"
import routerImpl from "@/router/index"

const axiosInstance = axios.create({
  baseURL: `${import.meta.env.VITE_SERVER_URL}/${import.meta.env.VITE_SERVER_KEY}`,
})



axiosInstance.interceptors.request.use((config) => {
  const userStore = useUserStore();
  if (userStore.user.token) {
    config.headers["Authorization"] = userStore.user.token
  }
  return config
})

axiosInstance.interceptors.response.use((response) => {
  return response.data
}, (error) => {
  if (error.response.data?.message) {
    ElMessage.error(error.response.data.message)
  }
  if (error.response.data?.statusCode === 401) {
    routerImpl.replace("/login")
    return Promise.reject(error)
  }
  return Promise.reject(error)
})

export default axiosInstance